package com.qu.waibao.account;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.qu.waibao.AppConfig;
import com.qu.waibao.MainActivity;
import com.qu.waibao.R;
import com.qu.waibao.baidu.LocationUtils;
import com.qu.waibao.baidu.MapActivity;
import com.qu.waibao.base.BaseActivity;
import com.qu.waibao.bean.Task;
import com.qu.waibao.bean.UserInfor;
import com.qu.waibao.interf.XnetCallBack;
import com.qu.waibao.my.adapter.GridImageAdapter;
import com.qu.waibao.network.ActionUtil;
import com.qu.waibao.network.HttpModeBase;
import com.qu.waibao.network.NetManager;
import com.qu.waibao.utils.GsonUtil;
import com.qu.waibao.utils.ToastUtil;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;
import info.wangchen.simplehud.SimpleHUD;

public class ShopAuthonticActivity extends BaseActivity implements View.OnClickListener{
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.one_TagFlowLayout)
    TagFlowLayout oneTag;
    @BindView(R.id.two_TagFlowLayout)
    TagFlowLayout twoTag;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_sure)
    TextView tv_sure;
    @BindView(R.id.iv_publish)
    ImageView iv_publish;
    @BindView(R.id.ll_back)
    LinearLayout ll_back;
    @BindView(R.id.et_name)
    EditText et_name;
    @BindView(R.id.et_legalman)
    EditText et_legalman;
    @BindView(R.id.et_legalpeopletel)
    EditText et_legalpeopletel;
    @BindView(R.id.et_address)
    EditText et_address;
    @BindView(R.id.et_linkman)
    EditText et_linkman;
    @BindView(R.id.et_linktel)
    EditText et_linktel;
    @BindView(R.id.tv_dingwei)
    TextView tv_dingwei;
    private StringBuilder business_main_builder = new StringBuilder();
    private StringBuilder business_second_builder = new StringBuilder();
    private String province = "";
    private String city = "";
    private String area = "";
    private String longitude = "";
    private String latitude = "";
    private String business_main = "";
    private String business_second = "";
    private GridImageAdapter imageAdapter;
    private Set<Integer> oneSelect;
    private Set<Integer> twoSelect;
    private HttpModeBase httpModeBase;
    private TagAdapter<Task.BusinessMainBean> oneAdapter;
    private TagAdapter<Task.BusinessSecondBean> twoAdapter;
    private List<LocalMedia> list;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case HttpModeBase.HTTP_SUCCESS:
                    String result = (String) msg.obj;
                    int position = msg.arg2;
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if(jsonObject.optInt("status") == 1){
                            String url = jsonObject.optString("src");
                            imageAdapter.addItem(url);
                            if(position < list.size() -1) {
                                position++;
                                imageSaveSet(list.get(position).getCompressPath(), position);
                            }
                        }else {
                            imageSaveSet(imageAdapter.getItems().get(position),position);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case HttpModeBase.HTTP_ERROR:
                    SimpleHUD.dismiss();
                    break;
            }
        }
    };
    private UserInfor userInfor;
    @Override
    protected boolean initBundle(Bundle bundle) {
        if(bundle != null){
            userInfor = (UserInfor) bundle.getSerializable("UserInfor");
        }
        return super.initBundle(bundle);
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_shop_authontic;
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        tv_title.setText("商家认证");
        tv_sure.setVisibility(View.VISIBLE);
        iv_publish.setVisibility(View.GONE);
        ll_back.setVisibility(View.GONE);
        tv_sure.setText("取消");
        httpModeBase = new HttpModeBase(handler,this);
        if(LocationUtils.Mylocation != null){
            province = LocationUtils.Mylocation.getProvince();
            city = LocationUtils.Mylocation.getCity();
            area = LocationUtils.Mylocation.getDistrict();
        }

    }

    @Override
    protected void initData() {
        super.initData();
        //图片
        imageAdapter = new GridImageAdapter(this, new GridImageAdapter.onAddPicClickListener() {
            @Override
            public void onAddPicClick() {
               if(ContextCompat.checkSelfPermission(ShopAuthonticActivity.this,
                       Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
                   openPhotos();
               }
            }
        });
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this,4);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setAdapter(imageAdapter);
        if(userInfor != null){
            province = userInfor.getProvince();
            city = userInfor.getCity();
            area = userInfor.getArea();
            latitude = userInfor.getLatitude();
            longitude = userInfor.getLongitude();
            et_name.setText(userInfor.getName());
            et_legalman.setText(userInfor.getLegalman());
            et_legalpeopletel.setText(userInfor.getLegalpeopletel());
            et_linkman.setText(userInfor.getLinkman());
            et_linktel.setText(userInfor.getLinktel());
            tv_dingwei.setText(userInfor.getProvince()+userInfor.getCity()+userInfor.getArea());
            et_address.setText(userInfor.getAddress());
            if(!TextUtils.isEmpty(userInfor.getImgs())){
                String[] images = userInfor.getImgs().split(",");
                imageAdapter.addList(Arrays.asList(images));
            }
        }
        getTasks();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                // 图片选择结果回调
                list = PictureSelector.obtainMultipleResult(data);
                if(list != null){

                   imageSaveSet(list.get(0).getCompressPath(),0);

                }
            }else if(requestCode == 0){
                latitude = String.valueOf(data.getDoubleExtra("latitude",0));
                longitude = String.valueOf(data.getDoubleExtra("longitude",0));
                String address = data.getStringExtra("address");
                et_address.setText(address);
                if(LocationUtils.Mylocation != null){
                    tv_dingwei.setText(LocationUtils.Mylocation.getProvince()
                            +LocationUtils.Mylocation.getCity()+LocationUtils.Mylocation.getDistrict());
                }
            }
        }
    }
    /**
     * 打开相册
     */
    public void openPhotos() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .maxSelectNum(3)// 最大图片选择数量
                .minSelectNum(1)// 最小选择数量
                .imageSpanCount(4)// 每行显示个数
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
                .previewImage(true)// 是否可预览图片
                .isCamera(true)// 是否显示拍照按钮
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .enableCrop(false)// 是否裁剪
                .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .isGif(false)// 是否显示gif图片
                .compress(true)// 是否压缩 true or false
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    public void imageSaveSet(String path,int position){
        httpModeBase.xutilsPostList(NetManager.BaseUrl,NetManager.image_save_set(),path,position,
                false);
    }
    @OnClick({R.id.tv_submit,R.id.tv_sure,R.id.ll_ding})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_submit:
                String name = et_name.getText().toString();
                String legalman = et_legalman.getText().toString();
                String legalpeopletel = et_legalpeopletel.getText().toString();
                String linkman = et_linkman.getText().toString();
                String linktel = et_linktel.getText().toString();
                String address = et_address.getText().toString();
                String images = getImages();
                if(TextUtils.isEmpty(name)){
                    ToastUtil.show(this,"请输入您公司名称");
                    return;
                }else if(TextUtils.isEmpty(legalman)){
                    ToastUtil.show(this,"请输入公司法人");
                    return;
                }else if(TextUtils.isEmpty(legalpeopletel)) {
                    ToastUtil.show(this, "请输入法人联系电话");
                    return;
                }else if(TextUtils.isEmpty(linkman)) {
                    ToastUtil.show(this, "请输入您的姓名");
                    return;
                }else if(TextUtils.isEmpty(linktel)) {
                    ToastUtil.show(this, "请输入您的手机号");
                    return;
                }
                //主营业务
                if(oneSelect != null && oneSelect.size() > 0){
                    for(Integer integer : oneSelect){
                        business_main_builder.append(oneAdapter.getItem(integer).getTitle()).append(",");
                    }
                    String main = business_main_builder.toString();
                    business_main = main.substring(0,main.length()-1);
                }else {
                    ToastUtil.show(this,"请选择主营业务");
                    return;
                }
                //副营业务
                if(twoSelect != null && oneSelect.size() > 0){
                    for(Integer integer : twoSelect){
                        business_second_builder.append(twoAdapter.getItem(integer).getTitle()).append(",");
                    }
                    String second = business_second_builder.toString();
                    business_second = second.substring(0,second.length()-1);
                }else {
                    ToastUtil.show(this,"请选择兼营业务");
                    return;
                }

                if(TextUtils.isEmpty(images)){
                    ToastUtil.show(this, "请上传您的营业执照");
                    return;
                }
                renzheng(images,name,legalman,legalpeopletel,address,linkman,linktel);
                break;
            case R.id.tv_sure:
                 onBackPressed();
                break;
            case R.id.ll_ding://定位
                startActivityForResult(new Intent(this, MapActivity.class),0);
                break;
        }
    }
    private String getImages(){
        StringBuilder builder = new StringBuilder();
        String uploadImages = "";
        if(imageAdapter != null){
            for(int i = 0;i<imageAdapter.getItems().size();i++){
                builder.append(imageAdapter.getItems().get(i)).append(",");
            }
            String images = builder.toString();
            if(!TextUtils.isEmpty(images)){
                uploadImages = images.substring(0,images.length()-1);
            }
        }
        return uploadImages;
    }
    public void renzheng(String images,String name,String legalman,String legalpeopletel,String address,String linkman,String linktel){
        SimpleHUD.showLoadingMessage(this,"",AppConfig.isCanCancel);
        Map<String,String> map = new HashMap<>();
        map.put("action", ActionUtil.user_plusinfo_set);
        map.put("userid", AppConfig.getString("userid"));
        map.put("name",name);
        map.put("business_main",business_main);
        map.put("business_second",business_second);
        map.put("legalman",legalman);
        map.put("legalpeopletel",legalpeopletel);
        map.put("province",province);
        map.put("city",city);
        map.put("area",area);
        map.put("address",address);
        map.put("longitude",longitude);
        map.put("latitude",latitude);
        map.put("linkman",linkman);
        map.put("linktel",linktel);
        map.put("idcard","");
        map.put("imgs",images);
        NetManager.getInstance().request(this, map, false, new XnetCallBack() {
            @Override
            public void onSuccess(String result, String msg) {
                ToastUtil.show(ShopAuthonticActivity.this,msg);
                startActivity(new Intent(ShopAuthonticActivity.this,MainActivity.class));
                finish();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                SimpleHUD.dismiss();
            }

            @Override
            public void onFinished() {
                SimpleHUD.dismiss();
            }
        });
    }

    public void getTasks(){
        Map<String,String> map = new HashMap<>();
        map.put("action",ActionUtil.business_list_get);
        NetManager.getInstance().request(this, map, true, new XnetCallBack() {
            @Override
            public void onSuccess(String result, String msg) {
                Task task = GsonUtil.createGson().fromJson(result,Task.class);
                oneAdapter = new TagAdapter<Task.BusinessMainBean>(task.getBusiness_main()) {
                @Override
                public View getView(FlowLayout parent, int position, Task.BusinessMainBean businessMainBean) {
                TextView textView = (TextView) LayoutInflater.from(ShopAuthonticActivity.this)
                        .inflate(R.layout.auth_layout,parent,false);
                    textView.setText(businessMainBean.getTitle());
                    return textView;
                   }
                };
                oneTag.setAdapter(oneAdapter);
                twoAdapter = new TagAdapter<Task.BusinessSecondBean>(task.getBusiness_second()) {
                    @Override
                    public View getView(FlowLayout parent, int position, Task.BusinessSecondBean businessSecondBean) {
                        TextView textView = (TextView) LayoutInflater.from(ShopAuthonticActivity.this)
                                .inflate(R.layout.auth_layout,parent,false);
                        textView.setText(businessSecondBean.getTitle());
                        return textView;
                    }
                };
                twoTag.setAdapter(twoAdapter);
                oneTag.setOnSelectListener(new TagFlowLayout.OnSelectListener() {
                    @Override
                    public void onSelected(Set<Integer> selectPosSet) {
                        oneSelect = selectPosSet;
                    }
                });
                twoTag.setOnSelectListener(new TagFlowLayout.OnSelectListener() {
                    @Override
                    public void onSelected(Set<Integer> selectPosSet) {
                        twoSelect = selectPosSet;
                    }
                });
           }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    public void onBackPressed() {
        if(userInfor != null) {
            finish();
        }else{
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
        }
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        business_main_builder = null;
        business_second_builder = null;
        handler = null;
        httpModeBase = null;
        oneSelect = null;
        twoSelect = null;
    }
}


